<template>
	<xn-form-container
		title="拨号盘"
		:width="300"
		:visible="visible"
		:body-style="{ background: 'rgba(0, 0, 0, 0.1)' }"
		:destroy-on-close="false"
		:footer="null"
		@close="close"
	>
		<a-form ref="formRef" :model="form" :rules="formRules">
			<a-form-item label="" name="phone">
				<a-input v-model:value="form.phone" placeholder="请输入电话号码" size="large">
					<template #addonBefore>
						<phone-outlined style="transform: scaleX(-1)" />
					</template>
				</a-input>
			</a-form-item>
			<div class="grid-container">
				<div
					v-for="(item, index) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]"
					:key="index"
					class="grid-item"
					@click="onEnterNum(item)"
				>
					{{ item }}
				</div>
				<div class="grid-item submit" @click="validateAndSubmit">
					<svg-icon name="phone-off" />
				</div>
				<div class="grid-item delete" @click="onDeletePhone">
					<svg-icon name="phone-del" />
				</div>
			</div>
		</a-form>
	</xn-form-container>
</template>

<script setup>
	const emits = defineEmits(['onPhoneConnect'])

	const visible = ref(false)
	const open = ({ phone = '', type }) => {
		Object.assign(form, {
			phone,
			type
		})
		visible.value = true
	}
	const close = () => {
		visible.value = false
	}

	const formRef = ref(null)
	const form = reactive({
		phone: '',
		type: ''
	})
	const formRules = {
		phone: [
			{ required: true, message: '电话号码不能为空', trigger: 'blur' },
			{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' }
		]
	}
	const onEnterNum = (num) => {
		form.phone += num.toString()
		formRef.value.clearValidate()
	}
	const validateAndSubmit = () => {
		formRef.value.validate().then(async () => {
			close()
			emits('onPhoneConnect', form.phone)
		})
	}
	const onDeletePhone = () => {
		if (!form.phone) {
			form.phone = ''
			return
		}
		form.phone = form.phone.substring(0, form.phone.length - 1)
		formRef.value.clearValidate()
	}

	defineExpose({
		open
	})
</script>

<style lang="less" scoped>
	.grid-container {
		display: grid;
		grid-auto-rows: 60px;
		grid-template-columns: auto auto auto;
		grid-gap: 30px;
		padding: 12px 12px;
		.grid-item {
			background: white;
			border-radius: 8px;
			text-align: center;
			line-height: 60px;
			font-size: 20px;
			font-weight: bold;
			cursor: pointer;
			user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
			-webkit-user-select: none;
		}

		.submit {
			background: #3d7fff;
			position: relative;
		}
		.delete {
			position: relative;
		}
		.svg-icon {
			position: absolute;
			top: 50%;
			left: 50%;
			margin: -10px 0 0 -10px;
		}
	}
</style>
